package com.xiong.wuliao;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.xiong.wuliao.entity.Urls;
import com.xiong.wuliao.mainfragment.MineFragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import okhttp3.Call;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
	// 返回
	private ImageButton myLoginButtonGoodBack;
	// 注册
	private TextView myLoginRegisterTextView;
	// 登录
	private RelativeLayout myLoginLoginLayout;
	private EditText myLoginPhotoEditText;
	private EditText myLoginPassWordEditText;
	// 第三方微博登陆
	private ImageView loginWeiBo;
	// 第三方微信登陆
	private ImageView loginWeiXin;
	// 第三方QQ登陆
	private ImageView loginQQ;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		ShareSDK.initSDK(LoginActivity.this, "key");
		init();
	}

	private void init() {
		findView();
		setListener();
	}

	/**
	 * 设置监听事件
	 */
	private void setListener() {
		// 返回监听
		myLoginButtonGoodBack.setOnClickListener(this);
		// 注册监听
		myLoginRegisterTextView.setOnClickListener(this);
		// 登录监听
		myLoginLoginLayout.setOnClickListener(this);

		loginWeiBo.setOnClickListener(this);
		loginWeiXin.setOnClickListener(this);
		loginQQ.setOnClickListener(this);
	}

	/**
	 * 初始化控件
	 */
	private void findView() {
		myLoginButtonGoodBack = (ImageButton) findViewById(R.id.myLoginButtonGoodBack);
		myLoginRegisterTextView = (TextView) findViewById(R.id.myLoginRegisterTextView);
		myLoginLoginLayout = (RelativeLayout) findViewById(R.id.myLoginLoginLayout);
		myLoginPhotoEditText = (EditText) findViewById(R.id.myLoginPhotoEditText);
		myLoginPassWordEditText = (EditText) findViewById(R.id.myLoginPassWordEditText);
		loginWeiBo = (ImageView) findViewById(R.id.loginWeiBo);
		loginWeiXin = (ImageView) findViewById(R.id.loginWeiXin);
		loginQQ = (ImageView) findViewById(R.id.loginQQ);
	}

	/**
	 * 普通点击事件的处理
	 *
	 * @param v
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.myLoginButtonGoodBack:
				LoginActivity.this.finish();
				break;
			case R.id.myLoginRegisterTextView:
				Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
				startActivity(intent);
				break;
			case R.id.myLoginLoginLayout:
				Log.e("------", "QQ");
				Login();
				break;
			case R.id.loginQQ:
				Log.e("------", "QQ");
				qqLogin();
				break;
			case R.id.loginWeiBo:
				Log.e("------", "微博");
				weiboLogin();
				break;
			case R.id.loginWeiXin:
				Log.e("------", "weiXin");
				weixinLogin();
				break;
		}
	}

	private void Login() {
		String phone = myLoginPhotoEditText.getText().toString();
		String passWord = myLoginPassWordEditText.getText().toString();
		if (phone.length() == 11 && 6 <= passWord.length() && passWord.length() <= 12) {
			OkHttpUtils.get(Urls.LoginPath)
					.params("phone", phone)
					.params("passWord", passWord)
					.execute(new StringCallback() {
						@Override
						public void onSuccess(String s, Call call, Response response) {
							JSONObject jsonObject = null;
							try {
								jsonObject = new JSONObject(s.trim());
								String result = jsonObject.getString("message");
								if (result.equals("OK")) {
									Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
									JSONObject object = jsonObject.getJSONObject("data");
									SharedPreferences sp = getSharedPreferences("kkUser", MODE_PRIVATE);
									SharedPreferences.Editor editor = sp.edit();
									editor.putBoolean("isLogin", true);
									editor.putString("id", object.getString("id"));
									editor.putString("userName", object.getString("userName"));
									editor.putString("passWord", object.getString("passWord"));
									editor.putString("phone", object.getString("phone"));
									editor.commit();
									LoginActivity.this.finish();
								} else {
									// 服务器验证失败（不存在该用户）
									Toast.makeText(LoginActivity.this, "输入错误", Toast.LENGTH_SHORT).show();
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}

						@Override
						public void onError(Call call, Response response, Exception e) {
							super.onError(call, response, e);
							Toast.makeText(LoginActivity.this, "服务器错误", Toast.LENGTH_SHORT).show();
						}
					});
		} else {
			// 电话或密码错误
			Toast.makeText(LoginActivity.this, "输入错误", Toast.LENGTH_SHORT).show();
		}
	}

/*
	7、删除授权信息
    由于ShareSDK所有的授权数据都存在PlatformDb中，所以“用户是否”授权，和“取消授权（清除授权信息）”的操作依据其实PlatformDb。在ShareSDK中，判断此平台是否授权的方法是isValid，而取消授权的方法是removeAccount，
    下面的代码演示客户端判断是否已经授权，如果授权就删除授权资料，否则就执行授权：
    Platform qzone = ShareSDK.getPlatform(QZone.NAME);
    If (qzone.isAuthValid()) {
        qzone.removeAccount(true);
    }
    qzone.setPlatformActionListener(paListener);
    //authorize与showUser单独调用一个即可
    qzone.authorize();//单独授权，OnComplete返回的hashmap是空的
    qzone.showUser(null);//授权并获取用户信息
    //isValid和removeAccount不开启线程，会直接返回。
*/

	/**
	 * 微信第三方登陆
	 */
	private void weixinLogin() {
		Platform weiXin = ShareSDK.getPlatform(Wechat.NAME);
		//回调信息，可以在这里获取基本的授权返回的信息，但是注意如果做提示和UI操作要传到主线程handler里去执行
		weiXin.setPlatformActionListener(new PlatformActionListener() {
			@Override
			public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                /* //输出所有授权信息
                String userName = arg0.getDb().getUserName();
                String userId = arg0.getDb().getUserId();
                String userPhoto = arg0.getDb().getUserIcon();   //获取的是用户的头像
                String userGender = arg0.getDb().getUserGender();*/     //获取用户的性别

			}

			@Override
			public void onError(Platform platform, int i, Throwable throwable) {
				throwable.printStackTrace();
			}

			@Override
			public void onCancel(Platform platform, int i) {

			}
		});
		//authorize与showUser单独调用一个即可
		// weibo.authorize();//单独授权,OnComplete返回的hashmap是空的
		weiXin.showUser(null);//授权并获取用户信息
		//移除授权
		//qq.removeAccount(true);
	}

	/**
	 * 微博第三方登陆
	 */
	private void weiboLogin() {
		Platform weiBo = ShareSDK.getPlatform(SinaWeibo.NAME);
		weiBo.setPlatformActionListener(new PlatformActionListener() {
			@Override
			public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                /* //输出所有授权信息
                String userName = arg0.getDb().getUserName();
                String userId = arg0.getDb().getUserId();
                String userPhoto = arg0.getDb().getUserIcon();   //获取的是用户的头像
                String userGender = arg0.getDb().getUserGender();*/     //获取用户的性别

			}

			@Override
			public void onError(Platform platform, int i, Throwable throwable) {
				throwable.printStackTrace();
			}

			@Override
			public void onCancel(Platform platform, int i) {

			}
		});
		weiBo.showUser(null);//授权并获取用户信息
	}

	/**
	 * QQ第三方登陆
	 */
	private void qqLogin() {
		Platform qq = ShareSDK.getPlatform(LoginActivity.this, QQ.NAME);
		qq.setPlatformActionListener(new PlatformActionListener() {
			@Override
			public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {

			}

			@Override
			public void onError(Platform platform, int i, Throwable throwable) {

			}

			@Override
			public void onCancel(Platform platform, int i) {

			}
		});
		qq.showUser(null);
	}
}
